<?php
namespace TwinPeaks\Core;

use TwinPeaks\Core\DataType\CBase;

class CFilterParam
{
	/**
	 * Datasources ids
	 */
	const POST_DATASOURCE   = 1;
	const GET_DATASOURCE    = 2;
	const COOKIE_DATASOURCE = 4;
	
	/**
	 * @var string
	 */
	private $name;
	
	/**
	 * @var TwinPeaks\Core\Datatype\CBase
	 */
	private $value;
	
	/**
	 * @var string
	 */
	private $dataKey;
	
	/**
	 * @var integer
	 */
	private $datasourceId;

	/**
	 * @return CFilterParam
	 */
	static function post($name, $value)
	{
		$paramObj = new static($name, $value);
		$paramObj->datasourceId = self::POST_DATASOURCE;
		return $paramObj;
	}
	
	/**
	 * @param string|array $nameMixed
	 * @param string|TwinPeaks\Core\Datatype\CBase $value
	 * @return void
	 */
	function __construct($nameMixed, $value)
	{
		if (is_string($nameMixed))
		{
			$this->name = $nameMixed;
			$this->dataKey = $nameMixed;
		}
		else if (is_array($nameMixed))
		{
			$this->dataKey = key($nameMixed);
			$this->name = $nameMixed[$this->dataKey];
		}
		
		$this->value = $value;
	}
	
	/**
	 * @return string
	 */
	final function getName()
	{
		return $this->name;
	}
	
	/**
	 * @return mixed
	 */
	function getValue()
	{
		switch ($this->datasourceId)
		{
			case self::POST_DATASOURCE:
				$DS_Array = $_POST;
				break;

			case self::GET_DATASOURCE:
				$DS_Array = $_GET;
				break;

			case self::COOKIE_DATASOURCE:
				$DS_Array = $_COOKIE;
				break;

			default:
				CSysException::filterUnknownDatasource();
		}

		if (!isset($DS_Array[$this->dataKey]))
		{
			if (($value = $this->value->get()) === null) // No default value
				CCommonException::filterNoParamValue($this->name)->_throw();
			else
				return $value;
		}
		else
			$value = $DS_Array[$this->dataKey];
		
		$this->value->set($value);

		return $this->value->get();
	}
}
